#include "../constant.h"

typedef struct qnode // 队列节点
{
    DataType data;
    qnode *next;
} * QNode;

typedef struct // rear入队 front出队，链表方向从front指向rear
{
    QNode front;
    QNode rear;
    int len;
} queue, *Queue;

#include "./queue.h"

Queue InitQueue()
{
    printf("[init] ring_linklist_queue\n");
    Queue q = (queue *)malloc(sizeof(queue));
    q->front = NULL;
    q->rear = NULL;
    return q;
}

int Empty(Queue q)
{
    return q->rear == NULL && q->front == NULL;
}

int Size(Queue q)
{
    return q->len;
}

int Pop(Queue &q)
{
    if (Empty(q))
    {
        warning("empty queue");
        return 0;
    }
    qnode *destory = q->front;
    DataType destoryVal = destory->data;
    q->front = q->front->next;
    q->len--;
    free(destory);
    if (!q->front)
    {
        q->rear = NULL;
    }
    return destoryVal;
}

int Push(Queue &q, DataType x)
{
    QNode node = (qnode *)malloc(sizeof(qnode));
    if (!node)
    {
        error("out of memory");
        return 0;
    }
    node->data = x;
    node->next = NULL;
    if (Empty(q))
    {
        q->front = node;
        q->rear = node;
    }
    else
    {
        q->rear->next = node;
        q->rear = node;
    }
    q->len++;
    return 1;
}

DataType Front(Queue q)
{
    if (Empty(q))
    {
        warning("empty queue");
        return 0;
    }
    return q->front->data;
}

DataType Back(Queue q)
{
    if (Empty(q))
    {
        warning("empty queue");
        return 0;
    }
    return q->rear->data;
}

void printf(Queue q)
{
    qnode *p = q->front;
    printf("[Queue] [ ");
    while (p != NULL)
    {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("]\n          ⬆front(deQueue)\n");
}
